package com.ruoyi.web.controller.fire;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.fire.domain.TUserUnit;
import com.ruoyi.fire.domain.dto.TUserUnitVO;
import com.ruoyi.fire.service.ITUserUnitService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.fire.domain.TUnit;
import com.ruoyi.fire.service.ITUnitService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 单位信息Controller
 *
 * @author ruoyi
 * @date 2025-11-02
 */
@Api(value = "TUnitController", tags = "物联单位")
@RestController
@RequestMapping("/system/unit")
public class TUnitController extends BaseController {
    @Autowired
    private ITUnitService tUnitService;

    @Autowired
    private ITUserUnitService userUnitService;

    /**
     * 新增单位信息
     */
    @ApiOperation("新增单位信息")
    @PreAuthorize("@ss.hasPermi('system:unit:add')")
    @Log(title = "单位信息", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody TUnit tUnit) {
        return toAjax(tUnitService.insertTUnit(tUnit));
    }

    /**
     * 查询单位信息列表
     */

    @ApiOperation("单位列表")
    @PreAuthorize("@ss.hasPermi('system:unit:list')")
    @GetMapping("/list")
    public TableDataInfo list(TUnit tUnit) {
        Long userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId)) {
            tUnit.setCreateUserId(userId);
            TUserUnitVO search = new TUserUnitVO();
            search.setUserId(userId);
            List<TUserUnit> tUserUnits = userUnitService.authUserUnitDetail(search);

            // 防止空指针异常
            if (tUserUnits != null && !tUserUnits.isEmpty()) {
                List<String> unitIds = tUserUnits.stream()
                        .map(TUserUnit::getUnitId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                tUnit.setUnitIds(unitIds);
            } else {
                // 当用户没有任何单位权限时，设置空列表避免查询所有数据
                tUnit.setUnitIds(Collections.emptyList());
            }
        }
        startPage();
        List<TUnit> list = tUnitService.selectTUnitList(tUnit);
        return getDataTable(list);
    }

    @ApiOperation("设备信息列表卡片")
    @PostMapping("/listCard")
    public TableDataInfo listCard(TUnit tUnit) {
        Long userId = SecurityUtils.getUserId();
        if (!SecurityUtils.isAdmin(userId)) {
            tUnit.setCreateUserId(userId);
            TUserUnitVO search = new TUserUnitVO();
            search.setUserId(userId);
            List<TUserUnit> tUserUnits = userUnitService.authUserUnitDetail(search);

            // 防止空指针异常
            if (tUserUnits != null && !tUserUnits.isEmpty()) {
                List<String> unitIds = tUserUnits.stream()
                        .map(TUserUnit::getUnitId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());
                tUnit.setUnitIds(unitIds);
            } else {
                // 当用户没有任何单位权限时，设置空列表避免查询所有数据
                tUnit.setUnitIds(Collections.emptyList());
            }
        }
        startPage();
        List<TUnit> list = tUnitService.selectTDeviceListCard(tUnit);
        return getDataTable(list);
    }

    /**
     * 导出单位信息列表
     */
    @PreAuthorize("@ss.hasPermi('system:unit:export')")
    @Log(title = "单位信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, TUnit tUnit) {
        Long userId = SecurityUtils.getUserId();
        tUnit.setCreateUserId(userId);
        List<TUnit> list = tUnitService.selectTUnitList(tUnit);
        ExcelUtil<TUnit> util = new ExcelUtil<TUnit>(TUnit.class);
        util.exportExcel(response, list, "单位信息数据");
    }

    /**
     * 获取单位信息详细信息
     */
    @ApiOperation("获取单位信息详细信息")
    @PreAuthorize("@ss.hasPermi('system:unit:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") String id) {
        return success(tUnitService.selectTUnitById(id));
    }


    /**
     * 修改单位信息
     */
    @ApiOperation("修改单位信息")
    @PreAuthorize("@ss.hasPermi('system:unit:edit')")
    @Log(title = "单位信息", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody TUnit tUnit) {
        return toAjax(tUnitService.updateTUnit(tUnit));
    }

    /**
     * 删除单位信息
     */
    @ApiOperation("删除单位信息")
    @PreAuthorize("@ss.hasPermi('system:unit:remove')")
    @Log(title = "单位信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable String[] ids) {
        return toAjax(tUnitService.deleteTUnitByIds(ids));
    }


    /**
     * 手动同步单位信息
     */
    @ApiOperation("手动同步单位信息")
    @Log(title = "手动同步单位信息", businessType = BusinessType.OTHER)
    @GetMapping("/push/{id}")
    public AjaxResult push(@PathVariable String id) {
        return toAjax(tUnitService.pushTUnit(id));
    }


    /**
     * 远程删除单位
     */
    @ApiOperation("远程删除单位信息")
    @Log(title = "单位信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/remoteDeletion/{unitId}")
    public AjaxResult remoteDeletion(@PathVariable String unitId) {
        return toAjax(tUnitService.remoteDeletion(unitId));
    }

    /**
     * 手动同步单位信息
     */
    @ApiOperation("先删除远程在删除本地单位信息")
    @Log(title = "删除单位信息", businessType = BusinessType.OTHER)
    @GetMapping("/remove/{unitId}")
    public AjaxResult removeByUnitId(@PathVariable String unitId) {
        return toAjax(tUnitService.removeByUnitId(unitId));
    }
}
